<?php
/*
 * @Descripttion: 控制器基类
 * @version: 1.0
 * @Author: Sam
 * @Date: 2020-05-22 16:40:41
 * @LastEditors: Sam
 * @LastEditTime: 2020-08-06 11:27:11
 */ 

namespace app\admin\controller;

use app\admin\model\SystemAdmin;
use basic\SystemBasic;
use behavior\system\SystemBehavior;
use service\HookService;
use think\Url;
use app\admin\model\SystemMenus;

/**
 * 基类 所有控制器继承的类
 * Class AuthController
 * @package app\admin\controller
 */
class AuthController extends SystemBasic
{
    /**
     * 当前登陆管理员信息
     * @var
     */
    protected $adminInfo;

    /**
     * 当前登陆管理员ID
     * @var
     */
    protected $adminId;

    /**
     * 当前管理员权限
     * @var array
     */
    protected $auth = [];

    protected $skipLogController = ['index','common'];

    /** @var string $route 当前控制器名称 */
    protected $controller = '';

    /** @var string $route 当前方法名称 */
    protected $action = '';

    /** @var string $route 当前路由uri */
    protected $routeUri = '';

    /** @var string $route 当前路由：分组名称 */
    protected $group = '';
    
    protected function initialize()
    {
        parent::initialize();
        if(!SystemAdmin::hasActiveAdmin()) return $this->redirect('Login/index');
        try{
            $adminInfo = SystemAdmin::activeAdminInfoOrFail();
        }catch (\Exception $e){
            return $this->failed(SystemAdmin::getErrorInfo($e->getMessage()),Url::build('Login/index'));
        }
        $this->adminInfo = $adminInfo;
        $this->adminId = $adminInfo['id'];
        $this->getActiveAdminInfo();
        $this->getRouteinfo();
        $this->auth = SystemAdmin::activeAdminAuthOrFail();
        $this->adminInfo->level === 0 || $this->checkAuth();
        $this->assign('_admin',$this->adminInfo);
        $menus = SystemMenus::menuList();
   
        $new_menus = [];
        foreach ($menus as $key => &$value) {
            $value['index']   = $value['module'].'/'.$value['controller'].'/'.$value['action'];
            $new_menus[$value['id']] = $value;
        }
      
        $this->assign('menus',$new_menus);
        HookService::listen('admin_visit',$this->adminInfo,'system',false,SystemBehavior::class);
    }

    
        /**
     * 解析当前路由参数 （分组名称、控制器名称、方法名）
     */
    protected function getRouteinfo()
    {
        // 控制器名称
        $controller = $this->controller = toUnderScore($this->request->controller());
        // 方法名称
        $action = $this->action = $this->request->action();
        // 控制器分组 (用于定义所属模块)
        $groupstr = strstr($this->controller, '.', true);
        $group    = $this->group = $groupstr !== false ? $groupstr : $this->controller;
        // 当前uri
        $routeUri = $this->routeUri = $this->controller . '/' . $this->action;
         
        $top_id   = $this->getTopId($controller,$action);
        // echo $top_id;die;
        $this->assign(compact('controller','action','group','routeUri','top_id'));
    }

    /**
     * @name: 获取一级菜单ID
     * @Author: Sam
     * @Date: 2020-06-09 15:01:12
     * @msg: 
     * @param {type} 
     * @return: {string}
     */
    protected function getTopId($controller,$action){
        $curent = SystemMenus::where(['controller'=>$controller,'action'=>$action])->field('id,pid')->find();
      
        if($curent->getData('pid') == 0){
            
            return $curent->id;
        }
        // 查找上级
        $parent = SystemMenus::where('id',$curent->getData('pid'))->field('id,pid')->find();
        if($parent->getData('pid') == 0){
            return $parent->id;
        }
        // 查找上上级
        $parent = SystemMenus::where('id',$parent->getData('pid'))->field('id,pid')->find();
        if($parent->getData('pid') == 0){
            return $parent->id;
        }
    }
    
    protected function checkAuth($action = null,$controller = null,$module = null,array $route = [])
    {
        static $allAuth = null;
        if($allAuth === null) $allAuth = SystemRole::getAllAuth();
        if($module === null) $module = $this->request->module();
        if($controller === null) $controller = $this->request->controller();
        if($action === null) $action = $this->request->action();
        if(!count($route)) $route = $this->request->route();
        if(in_array(strtolower($controller),$this->skipLogController,true)) return true;
        $nowAuthName = SystemMenus::getAuthName($action,$controller,$module,$route);
        $baseNowAuthName =  SystemMenus::getAuthName($action,$controller,$module,[]);
        if((in_array($nowAuthName,$allAuth) && !in_array($nowAuthName,$this->auth)) || (in_array($baseNowAuthName,$allAuth) && !in_array($baseNowAuthName,$this->auth)))
            exit($this->failed('没有权限访问!'));
        return true;
    }


    /**
     * 获得当前用户最新信息
     * @return SystemAdmin
     */
    protected function getActiveAdminInfo()
    {
        $adminId = $this->adminId;
        $adminInfo = SystemAdmin::getValidAdminInfoOrFail($adminId);
        if(!$adminInfo) $this->failed(SystemAdmin::getErrorInfo('请登陆!'));
        $this->adminInfo = $adminInfo;
        SystemAdmin::setLoginInfo($adminInfo);
        return $adminInfo;
    }
}